﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Configuration;
using Model;
using Utility.ExtensionFunc;

namespace DAL
{
    public class UserRepository : RepositoryBase
    {

        private static UserRepository userRepo;

        private UserRepository()
        {
            xmlDoc = new XmlDocument();
            xmlPath = basicPath + ConfigurationManager.AppSettings["UserPath"].ToString();
        }

        public static UserRepository Instrance
        {
            get
            {
                if (null == userRepo) { userRepo = new UserRepository(); }
                return userRepo;
            }
        }

        public List<USER> LoadUserXML()
        {
            lock (thisLock)
            {
                List<USER> userList = new List<USER>();
                this.LoadXML();
                userList = xmlRoot.ConvertToEntity<USER>(USER.NODE);
                return userList;
            }
        }

        public bool AddUser(USER user)
        {
            lock (thisLock)
            {
                List<USER> userList = this.LoadUserXML();
                if (userList.Count(c => c.ID == user.ID) > 0)
                {
                    return false;
                }
                XmlElement newUserElem = user.ConvertToXML<USER>(xmlDoc, USER.NODE);
                if (null == newUserElem)
                {
                    return false;
                }
                xmlRoot.AppendChild(newUserElem);
                this.SaveXML();
                return true;
            }

        }

        public bool UpdateUser(USER user)
        {
            lock (thisLock)
            {
                this.LoadXML();
                foreach (XmlNode node in xmlRoot.SelectNodes(USER.NODE))
                {

                    if (node.SelectSingleNode(USER.NODE_ID).InnerText == user.ID)
                    {
                        node.SelectSingleNode(USER.NODE_ID).InnerText = user.ID;
                        node.SelectSingleNode(USER.NODE_NAME).InnerText = user.NAME;
                        node.SelectSingleNode(USER.NODE_BALANCE).InnerText = user.BALANCE.ToString();
                        node.SelectSingleNode(USER.NODE_RIGHT).InnerText = user.RIGHT.ToString();
                    }
                }

                this.SaveXML();
                return true;

            }
        }
    }
}
